#include "gun.h"
#include <QDebug>
Gun::Gun(Player* own)
{
	owner = own;

	clipSize = 20;
	recoilTime = 120;
	reloadTime = 10 * 360;
	//reloadTime = 0;


	isFirePressed = false;
	bullets.clear();

	clip = clipSize;
	recoil = 0;
	reload = 0;

	isRealoading = false;
}

bool Gun::fire(qreal x, qreal y, qreal ang)
{
	Bullet * bullet = new Bullet(QPointF(x, y), ang, owner);
	bullets.append(bullet);
	connect(bullet, SIGNAL(hitPolygon()), this, SLOT(onHitPolygon()));
	connect(bullet, SIGNAL(hitPlayer(Player*,Player*)), this,
			SLOT(onHitPlayer(Player*,Player*)));
	clip--;

	if (clip <= 0)
	{
		startReloading();
	}

	emit
	gunFired(bullet);
	return true;
}

int Gun::getStatus()
{
	if (isRealoading)
	{
		return 1;
	}
	return 0;
}

int Gun::getClipSize()
{
	return clipSize;
}
int Gun::getClip()
{
	return clip;
}
int Gun::getReloadTime()
{
	return reloadTime;
}
int Gun::getReload()
{
	return reload;
}

void Gun::startReloading()
{
	reload = 0;
	isRealoading = true;
}

void Gun::finishReloading()
{
	reload = reloadTime;
	isRealoading = false;
	clip = clipSize;
}

void Gun::setGunAngle(qreal a)
{
	angle = a;
}

qreal Gun::getGunAngle()
{
	return angle;
}

void Gun::resetGun()
{
	recoil = 0;
	isFirePressed = false;
	finishReloading();
}

void Gun::makeShootingPossible()
{
	recoil = 0;
	if (isRealoading)
	{
		finishReloading();
	}
}

void Gun::firePressed()
{
	isFirePressed = true;
}
void Gun::fireReleased()
{
	isFirePressed = false;
}

bool Gun::updateGun()
{
	if (recoil > 0)
	{
		recoil -= 20;
	}
	if (isRealoading)
	{
		reload += 20;
		if (reload >= reloadTime)
		{
			isRealoading = false;
			clip = clipSize;
		}
	}
	if (isFirePressed)
	{
		if (owner != 0)
		{
			if (clip > 0)
			{
				if (recoil <= 0 && !isRealoading)
				{
				    recoil = recoilTime;
				    return true;
				}
			}
		}
	}
	return false;
}

QVector<Bullet*> Gun::getBullets()
{
	return bullets;
}

Player* Gun::getOwner()
{
	return owner;
}

void Gun::setOwner(Player* o)
{
	owner = o;
}

int Gun::getRecoil()
{
	return recoil;
}
int Gun::getRecoilTime()
{
	return recoilTime;
}

void Gun::onHitPlayer(Player* p1, Player* p2)
{
	qDebug() << "gun emit hit";
	emit hitPlayer(p1, p2);
}

void Gun::onHitPolygon()
{
	Bullet* b = static_cast<Bullet*> (sender());
	if (owner->getIsRemote())
		qDebug() << "hit polygon";
	bullets.remove(bullets.indexOf(b));
}
